package com.CmJava.tomcat;

import com.CmJava.servlet.DispatcherServlet;
import org.apache.catalina.*;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;

import java.io.File;


public class Tomcat {
    public void start(String port, String hostName){
        org.apache.catalina.startup.Tomcat tomcat = new org.apache.catalina.startup.Tomcat();

        Server server = tomcat.getServer();
        Service service = server.findService("Tomcat");

        Connector connector = new Connector();
        connector.setPort(Integer.parseInt(port));

        Engine engine = new StandardEngine();
        engine.setDefaultHost(hostName);


        Host host = new StandardHost();
        host.setName(hostName);


        String contextPath="";
        String htmlPath = this.getClass().getResource("/").getFile();
        htmlPath = new File(htmlPath+"static").getAbsolutePath();
        Context context = tomcat.addWebapp(contextPath, htmlPath);
        context.addLifecycleListener(new org.apache.catalina.startup.Tomcat.FixContextListener());

        //维护起层级关系
        host.addChild(context);
        engine.addChild(host);
        service.setContainer(engine);
        service.addConnector(connector);

        tomcat.addServlet(contextPath,"dispatcher",new DispatcherServlet());
        context.addServletMappingDecoded("/test","dispatcher");

        try {
            tomcat.start();
            tomcat.getServer().await();
        } catch (Exception e) {
            //因为没有设置jsp的servlet，这里会报java.lang.ClassNotFoundException: org.apache.jasper.servlet.JspServlet
            //我直接忽略了。。
        }
    }
}
